<template>
	<view>
		<view class="search-box">
			<uni-search-bar @input="input" :radius="100" placeholder="搜索" cancelButton="none"></uni-search-bar>
		</view>
		<view class="sugg-list" v-if="searchResults.length !== 0 ">
			<view class="query-box" v-for="(item,i) in searchResults" :key="i" @click="gotoGoodsDetail(item.goods_id)">
				<view class="result-bow">{{ item.goods_name }}</view>
				<uni-icons type="forward" size="14"></uni-icons>
			</view>
		</view>
		<view class="history-box" v-else>
			<view class="history-title">
				<text>历史记录</text>
				<uni-icons type="trash" size="17" @click="clearHistory()"></uni-icons>
			</view>
			<view class="history-list">
				<uni-tag v-for="(item,index) in finalHistory" :key="index" :text="item" @click="gotoHistory(item)">
				</uni-tag>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				timer: null,
				searchResults: [],
				keywords: '',
				historyList: []
			};
		},
		onLoad() {
			this.historyList = JSON.parse(uni.getStorageSync('SearhHistory')) || []
		},
		methods: {
			input(e) {
				clearTimeout(this.timer)
				this.timer = setTimeout(() => {
					this.keywords = e
					this.getSearchList()
					this.saveSearchHistory(e)
				}, 500)
			},
			async getSearchList() {
				if (this.keywords) {
					const {
						data: res
					} = await uni.$http.get('api/public/v1/goods/qsearch?query=' + this.keywords)
					if (res.meta.status !== 200) {
						return uni.$showMsg()
					}
					this.searchResults = res.message
				} else {
					this.searchResults = []
				}
			},
			saveSearchHistory(input) {
				let mySet = new Set(this.historyList)
				mySet.delete(input)
				mySet.add(input)
				this.historyList = [...mySet]
				uni.setStorageSync('SearhHistory', JSON.stringify(this.historyList))
			},
			gotoHistory(input) {
				uni.navigateTo({
					url:'/subpkg/goods_list/goods_list?query=' + input
				})
			},
			gotoGoodsDetail(id) {
				uni.navigateTo({
					url: '/subpkg/goods_detail/goods_detail?goods_id=' + id
				})
			},
			clearHistory() {
				uni.clearStorageSync('SearhHistory')
				this.historyList = []
			}
		},
		computed: {
			finalHistory() {
				return [...this.historyList].reverse()
			}
		}
	}
</script>

<style lang="scss">
	.search-box {
		position: sticky;
		top: 0;
		z-index: 999;
	}

	.sugg-list {
		padding: 0 5px;

		.query-box {
			font-size: 12px;
			display: flex;
			margin: 5px 0;
			padding: 13px 0;
			justify-content: space-between;
			border-bottom: 1px solid #efefef;

			.result-bow {
				margin-left: 3px;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}
		}
	}

	.history-box {
		padding: 0 5px;

		.history-title {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 13px;
			height: 40px;
			border-bottom: 1px solid #efefef;
		}

		.history-list {
			display: flex;
			flex-wrap: wrap;
		}
	}

	.uni-tag {
		margin-top: 5px;
		margin-right: 5px;
	}
</style>
